package cs.sy.common.util;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.net.URISyntaxException;
import java.net.URL;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderFactoryImpl;

/*
 * @description:根据IP获得所在城市天气预报
 * @author:寒江独钓
 * @blog:http://canglangxuan.com
 * @alert:文件编码为UTF-8格式，windows下eclipse用户需要使光标在此java文件内，
 * 然后点击Edit->SetEncoding修改编码为UTF-8
 */

public class WeatherReport {
	/* 根据腾讯API获得您所在城市 */
	public String getCity() throws IOException {
		URL location = new URL("http://fw.qq.com/ipaddress");
		BufferedReader in = new BufferedReader(new InputStreamReader(location
				.openStream(), "gb2312"));// 必须使用gb2312编码
		String ocity = in.readLine().split("\",\"")[3];
		String city = ocity.substring(0, ocity.indexOf("\")"));
		if (city.equals(""))// 直辖市城市名称显示在第二项
			city = in.readLine().split("\",\"")[2];
		return city;
	}

	/* 根据城市名称利用Google API获得天气 */
	public String getWeather(String cityName, String fileAddr)
			throws URISyntaxException, IOException,
			ParserConfigurationException, SAXException {
		String content, weather = null;

		/*
		 * 保存网页
		 */
		File file = new File(fileAddr);
		if (!file.exists())
			try {
				file.createNewFile();
			} catch (IOException e1) {
				e1.printStackTrace();
			}
		URL url = new URL("http://www.google.com/ig/api?hl=zh_cn&weather="
				+ cityName);
		InputStream inputstream = url.openStream();
		BufferedReader in = new BufferedReader(new InputStreamReader(
				inputstream, "gb2312"));
		Writer out = new BufferedWriter(new OutputStreamWriter(
				new FileOutputStream(file)));
		while ((content = in.readLine()) != null) {
			out.write(content);
		}
		out.close();
		in.close();

		/*
		 * 解析xml
		 */
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		DocumentBuilder builder = factory.newDocumentBuilder();
		Document doc = builder.parse(file);
		NodeList cnodelist = (NodeList) doc.getElementsByTagName(
				"current_conditions").item(0).getChildNodes();
		// 实时天气
		weather = "实时天气：\n"
				+ cnodelist.item(0).getAttributes().item(0).getNodeValue()
				+ "\n温度:"
				+ cnodelist.item(2).getAttributes().item(0).getNodeValue()
				+ "℃\n"
				+ cnodelist.item(3).getAttributes().item(0).getNodeValue()
				+ "\n图片网址："
				+ cnodelist.item(4).getAttributes().item(0).getNodeValue()
				+ "\n"
				+ cnodelist.item(5).getAttributes().item(0).getNodeValue()
				+ "\n====================================\n\n未来三天天气预报：\n";
		// 预报天气
		for (int i = 0; i < 4; i++) {
			NodeList fnodlist = (NodeList) doc.getElementsByTagName(
					"forecast_conditions").item(i).getChildNodes();
			weather += fnodlist.item(0).getAttributes().item(0).getNodeValue()
					+ "\n温度:"
					+ fnodlist.item(1).getAttributes().item(0).getNodeValue()
					+ "/"
					+ fnodlist.item(2).getAttributes().item(0).getNodeValue()
					+ "°C\n图片网址："
					+ fnodlist.item(3).getAttributes().item(0).getNodeValue()
					+ "\n天气："
					+ fnodlist.item(4).getAttributes().item(0).getNodeValue()
					+ "\n====================================\n";

		}
		return weather;

	}

	public static void main(String args[]) throws URISyntaxException,
			IOException, ParserConfigurationException, SAXException {
		WeatherReport wr = new WeatherReport();
		String weather = wr.getWeather(wr.getCity(), "weather.xml");
		System.out.println(wr.getCity() + "的天气情况是：\n\n" + weather);
	}
}